// pages/gaokao/gk_exam_registrationInfo/gk_exam_registrationInfo.js
const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');

Page({
  data: {
    // 1. 基础信息（保持不变）
    base_candidate_info: {
      id_number: '',
      phone: '',
      name: '',
      gender: '',
      birth_date: '',
      ethnicity_id: '',
      foreign_language_id: '',
      political_status_id: ''
    },
    // 2. 报考学籍信息（新 zikao_academic_info）
    zikao_academic_info: {
      english_name: '',
      registered_residence_code: '',
      pre_education_code: '',
      occupation_code: '',
      major_code: '',
      registration_city_code: '',
      registration_point_code: '',
      is_currently_student: 0,
      household_address: ''
    },
    // 3. 个人附加信息（zikao_exam_extra）
    zikao_exam_extra: {
      office_phone: '',
      postal_code: '',
      address: '',
      mobile_phone2: '',
      work_unit: '',
      email: '',
      work_unit_address: '',
      current_residence: '',
      police_school_student_id: '',
      police_officer_number: '',
      registration_time: '',      // 会自动格式化
      // 隐藏字段： police_review_flag, attend_exam_punctually
    },

    expanded: {
      base: false,
      academic: false,
      extra: false
    },

    // 映射容器：存放 code->name
    idToName: {
      ethnicity: {},
      political: {},
      writtenLang: {},
      // 学籍映射
      residence: {},
      preEducation: {},
      occupation: {},
      major: {},
      city: {},
      registrationPoint: {},
      address:{},
      // 附加映射
      workUnitAddress: {}
    }
  },

  async onLoad() {
    // 从本地读取三部分信息
    const B = wx.getStorageSync('base_candidate_info')  || {};
    let A = wx.getStorageSync('zikao_academic_info')  || {};
    let E = wx.getStorageSync('zikao_exam_extra')       || {};
    // 本地不存在数据，从后端拉取
    if(JSON.stringify(A) === '{}'){
      await tools.loadExamInfo(B.id_number)
      A = wx.getStorageSync('zikao_academic_info')  || {};
      E = wx.getStorageSync('zikao_exam_extra')       || {};
    }
    // 格式化部分日期
    if (B.birth_date)    B.birth_date = tools.formatDate(B.birth_date);
    if (E.registration_time) E.registration_time = tools.formatDate(E.registration_time);

   this.setData({
      base_candidate_info: B,
      zikao_academic_info: A,
      zikao_exam_extra: E
    });
    await this.fetchNameMappings();
  },

  fetchNameMappings() {
    // 户籍类型枚举（唯一来源）
    const residenceOptions = [
      { code: 1, name: '城镇' },
      { code: 2, name: '农村' },
      { code: 255, name: '未采集' }
    ];
  
    const { zikao_academic_info: A } = this.data;
    const residenceCode = A?.registered_residence_code;
  
    if (residenceCode !== undefined && residenceCode !== null) {
      const hit = residenceOptions.find(item => item.code === residenceCode);
      this.setData({
        [`idToName.residence.${residenceCode}`]: hit ? hit.name : ''
      });
    }
  
    /* 其余字段保持原远程拉取逻辑 */
    const { base_candidate_info: B, zikao_exam_extra: X } = this.data;
    const mapCfg = [
      { key:'ethnicity',    field:'ethnicity_id',          url:id=>`/ethnicity/info?id=${id}`},
      { key:'political',    field:'political_status_id',   url:id=>`/politicalstatus/info?id=${id}`},
      { key:'writtenLang',  field:'foreign_language_id',   url:id=>`/foreignlanguage/info?id=${id}`},
      { key:'preEducation', field:'pre_education_code',    url:id=>`/zikao/education/${id}`},
      { key:'occupation',   field:'occupation_code',       url:code=>`/zikao/occupation/${code}`},
      { key:'major',        field:'major_code',            url:id=>`/major/info?id=${id}`},
      { key:'city',         field:'registration_city_code',url:code=>`/city/infoByCode?cityCode=${code}`},
      { key:'registrationPoint',field:'registration_point_code',url:id=>`/chengkao/examSite/${id}`},
      { key:'address',field:'household_address',url:code=>`/gaokao/GkRegisteredResidence/${code}`},
      { key:'workUnitAddress',field:'work_unit_address',   url:code=>`/gaokao/GkCounty/${code}`}
    ];
  
    const promises = [];
    mapCfg.forEach(({ key, field, url }) => {
      const val = B?.[field] ?? A?.[field] ?? X?.[field];
      if (val == null) return;
      promises.push(
        http.get(url(val)).then(res => {
          if (res.statusCode === 200 && res.data?.data) {
            this.setData({ [`idToName.${key}.${val}`]: res.data.data.name });
          } else if (res.statusCode === 200 && res.data?.cityName) {
            this.setData({ [`idToName.${key}.${val}`]: res.data.cityName });
          }
        })
      );
    });
    return Promise.all(promises).catch(console.error);
  },

  toggleSection(e) {
    const sec = e.currentTarget.dataset.section;
    this.setData({ [`expanded.${sec}`]: !this.data.expanded[sec] });
  },

});
